/**
 * Created by jeff.jiang on 2015/9/14.
 * 项目模块js
 */

var template_stage = 0;
var currentEditTask;
$(document).ready(function () {
    init();
});

function init() {

    /* 绑定鼠标移入移开事件 */
    $(document).on("mouseover", "#task_list tr,.task-member-list li", function () {
        $(this).find(".icon-remove2").show();
        $(this).css("background-color","#e4e4e4");
    });

    $(document).on("mouseout", "#task_list tr,.task-member-list li", function () {
        $(this).find(".icon-remove2").hide();
        $(this).css("background-color","#ffffff");
    });

    /*
    $('[data-toggle="drop-select"]').click(function (e) {
        $(this).information('dropSelect',{
            onFa:true,
            eles:'drop-select-div',
            List:'drop-select-menu',
            elem:'drop-select'
        });
        e.stopPropagation();
    });
    */

    $(document).on("click",'[data-toggle="drop-select"]',function (e) {
        $(this).information('dropSelect');
        e.stopPropagation();
    });

    $(document).on("click",".drop-select-menu li",function (e) {
        $(this).information('dropOption');
        e.stopPropagation();
    });

    $('[data-toggle="Task_onc"]').click(function (e) {
        $(this).information('Task',{
            onFa:false,
            eles:'add_text',
            List:'add_con_list',
            elem:'Task-t'
        });
        e.stopPropagation();
    });

    $(".Screening_Singular").find("li").on({
        click:function(e){
            $(this).information('Task_list',{
                onFa:true,
                intext:'types',
                elem:'choose_class'

            });
            e.stopPropagation();
        }
    });

    /* 删除任务 */
    $(document).on("click", "#task_list .icon-remove2", function () {
        // removeTask($(this).parents("tr"));
		var task_id = $(this).parents("tr").attr('data-id');
		var delTaskId = $('#delTaskId').val();
		if(task_id != 0){
			$('#delTaskId').val(delTaskId+','+task_id);
		}
		$(this).parents("tr").remove();
    });
	

    /* 删除任务成员 */
    $(document).on("click", ".task-member-list .icon-remove2", function () {
        removeTaskMember($(this).parents("li"));
    });

    /* 选择阶段 */
    $(document).on("click", "#template-task-stage a", function () {
        selectTemplateTaskStage(this);
        template_stage = $(this).data("id");
    });
    $(document).on("click", "#task-stage a", function () {
        selectTaskStage(this);
        template_stage = $(this).data("id");
    });

    /* 默认阶段 */
    template_stage = $("#template-task-stage .selected a").data("id");

    $(document).on("click", "#task-stage .icon-remove2", function () {
        removeTaskStage($(this).parent());
    });


    $(document).on("click",".icon-add",function(){
        $(this).parents(".income-add").find(".drop-div").show();
    });

    $(document).on("mouseleave",".drop-div",function(){
        $(this).hide();
    });
    $(document).on("click",".task-doc .drop-div li a",function(){
        $(this).parents(".drop-div").hide();
    });

    /*添加子任务按钮
     $("#task_list .parent-task").on("click",".add-sub-task",function(){
        addTemplateSubTask($(this).parent());
    });*/
  
   /* 切换到编辑模式
     $("#task_list tr").on("click","td:has(input)", function(){
     editTemplateTask($(this).parents("tr"));
     });*/
}

function stageSort(){
    if($("#templateId").val()!=''){
        var ids = '';
        $.each($(".task-stage").find("li"),function(i,u){
            ids += $(u).find("a").eq(0).data("id") + ",";
        });
        ids = ids.substring(0,ids.length-1);
        $.ajax({
            url:web_path + 'project/set/updateTemplateStage.htm',
            type:'post',
            dataType:'json',
            data:{ids:ids,templateId:$("#templateId").val()},
            cache:false,
            success:function(data) {
            },
            error:function(msg) {
                alert(msg);
            }
        });
    }
}

/**
 * 选择模板阶段
 */
function selectTemplateTaskStage(stageObj) {
    var sid = $(stageObj).data("id");
    var stxt = $(stageObj).text();
    $("#task-percent").parent().find("label").html(stxt + " 的阶段");
	$("#task_list2").html(stxt);
    $(stageObj).parents("ul").children().removeClass("selected");
    var aa = $(stageObj).parents("li");
    $(stageObj).parents("li").addClass("selected");
    $("#task_list tr").hide();
    $("#task_list [data-stage=" + sid + "]").show();
    var process = 0;
    $("#task_list [data-stage="+ sid +"]").each(function(){
        if($(this).find(".process").val() == undefined || $(this).find(".process").val()==""){
            process += 0;
        }else{
            process += parseFloat($(this).find(".process").val().replace("%",""));
        }
    });
    $("#task-percent").html(process + "%");
}

/**
 * 选择模板阶段
 */
function selectTaskStage(stageObj) {
    var sid = $(stageObj).data("id");
    var stxt = $(stageObj).text();
    $(stageObj).parents("ul").children().removeClass("selected");
    $(stageObj).parents("ul").find(".icon-remove2").hide();
    $(stageObj).parents("li").addClass("selected");
    $(stageObj).parents("li").find(".icon-remove2").show();
}

/**
 * 添加阶段
 */
function addTemplateTaskStage(obj) {
    var sid = $(obj).data("id");
    var sname = $(obj).text();
    $("#task_list2").html(name);
    addTemplateTaskStageById(sid, sname);
    $(obj).parents(".input_dowm").hide();
    template_stage = sid;
}

/**
 * 添加阶段
 */
function addTemplateTaskStageById(sid, sname) {
    if ($("#template-task-stage [data-id=" + sid + "]").length == 0) {
        var html = '<li><a data-id="' + sid + '">' + sname + '</a><span class="icon-remove2"></span></li>';
        $("#template-task-stage").append(html);
        selectTemplateTaskStage($("#template-task-stage a:last"));
    }
}

/**
 * 删除阶段
 * @param stageObj
 */
function removeTemplateTaskStage(obj) {
    var stage = $(obj).find("a").data("id");
    $(obj).remove();
    $("#task_list [data-stage=" + stage + "]").remove();
}

/**
 * 删除阶段
 * @param obj
 */
function removeTaskStage(obj) {
    var stage = $(obj).find("a").data("id");
    $(obj).remove();
    $("#task_list [data-stage=" + stage + "]").remove();
}


/**
 * 删除任务
 * obj 任务tr对象
 */
function removeTask(obj) {
    var tid = $(obj).data("id");
    var pid = $(obj).data("pid");
    if (pid == 0) {
        var aa = $("#task_list [data-pid=" + tid + "]");
        $("#task_list [data-pid=" + tid + "]").remove();
    }
    $(obj).remove();
    var sid = $(obj).data("stage");
    var process = 0;
    $("#task_list [data-stage="+ sid +"]").each(function(){
        if($(this).find(".process").val() == undefined){
            process += 0;
        }else{
            process += parseFloat($(this).find(".process").val().replace("%",""));
        }
    });
    var stageStep = parseFloat($("#task-percent").text().replace("%",""));
    $("#task-percent").html(process+"%");
    var totalStageStep = parseFloat($("#totalStageStep").text().replace("%",""));
    $("#totalStageStep").text(changeTwoDecimal_f(totalStageStep-stageStep+process)+"%");
}


/**
 * 添加模板任务
 * @param obj
 */
function addTemplateTask() {
	
	//角色和审核组都是根据项目类型id去获取应对的json数据，所以要先选项目类型
	if(projectTypeIds == 0){
		alert('请先选择项目类型');
		return false;
	}
	
    saveTemplateTask();
    // var id = getRandomTaskId();
    if(template_stage == undefined){
        template_stage = -1;
    }
    var html = '<tr class="parent-task"edit_flag="1" data-stage="'+template_stage +'" data-id="0" data-pid="0" onmousemove="remove_tag(this);" onmouseout="hide_tag(this);">';
    html += '<td class="td1"><span class="hide"></span><input type="text" class="" name="taskName['+template_stage+'][]" placeholder="输入任务名称" /></td>';
	
	//添加子任务暂时隐藏
    // html += '<td class="add-sub-task td2">+子任务</td>';
	
    html += '<td  class="td2"><span class="hide">绩效</span><input type="text" class="" name="performance['+template_stage+'][]" placeholder="绩效" /></td>';
	html +='<td class="td3"><span class="hide"></span><select name="typeId['+template_stage+'][]"><option value="">项目角色</option>';

	if(task[projectTypeIds] && task[projectTypeIds]['role']){
		$.each(task[projectTypeIds]['role'], function (k, ele) {
			html += '<option value="'+k+'" class="sl_'+k+'">'+ele.name+'</option>';
		});

	}
	html +='</select></td>';
	
	// html +='<td  class="td4"><span class="hide">周期</span><input type="text" class="" name="taskTime['+template_stage+'][]" placeholder="周期" /></td>';
	html +='<td  class="td4"><span class="hide">专家审核</span><select name="roleId['+template_stage+'][]">';
		if(task[projectTypeIds] && task[projectTypeIds]['auditor']){
			console.log(task[projectTypeIds]['auditor']);
			$.each(task[projectTypeIds]['auditor'], function (k, ele) {
				html += '<option value="'+k+'" class="sl_'+k+'">'+ele.name+'</option>';
			});

		}
	html += '</select></td>'
	
    html +='<td  class="td5"><span class="hide"></span><select name="audit_rank['+template_stage+'][]"><option value="">二次审核</option><option value="1" class="sl_1">商务审核</option><option value="2" class="sl_2">客户审核</option>';
	
	// if(task[projectTypeIds] && task[projectTypeIds]['auditor']){
		// $.each(task[projectTypeIds]['auditor'], function (k, ele) {
			// html += '<option value="'+k+'">'+ele.name+'</option>';
		// });

	// }
	// '<option value="专家审核">专家审核</option><option value="商业审核">商业审核</option>
	html +='</select></td>'
    html += '<td  class="td6"><span class="hide">备注</span><input type="text" class="" name="remark['+template_stage+'][]" placeholder="备注" /></td>';
	
	var level = $('#task_list [data-stage=' + template_stage + ']').length + 1;
	
	html += '<td class="w40"><span class="hide"></span><input type="text" class="process" name="level['+template_stage+'][]" value="'+level+'" placeholder=""/></td>';
    html += '<td><div class="icon-remove2" style="width:16px;height=16px;cursor:pointer;background:#fff;"onmousemove="remove_tag(this);" onmouseout="hide_tag(this);"></div></td>';
	
    html += '</tr>';
    $("#task_list").append(html);
    $("#task_list [edit_flag=1]").find("input").eq(0).focus();
    i++;
}
/**
 * 添加子任务
 * @param ptask
 */
function addTemplateSubTask(obj) {
    var ptask = $(obj);
    var pid = ptask.data("id");
    var subTasks = $("#task_list [data-pid=" + pid + "]");
    var html = '';
    if(template_stage == undefined){
        template_stage = -1;
    }
    html = '<tr class="sub-task" style="width:723px;"edit_flag="1" data-stage="'+template_stage +'" data-id="0" data-pid="'+pid+'" onmousemove="remove_tag(this);" onmouseout="hide_tag(this);">';
    html += '<td  class="td1"><span class="hide" >输入子任务名称</span><input type="text" class="" name="taskName['+template_stage+'][]" placeholder="输入子任务名称"/></td>';
    html += '<td class="td2"><p style="display:none;"></p></td>';
	
	html +='<td  class="td3"><span class="hide"></span><select name="typeId['+template_stage+'][]"><option value="">项目角色</option>';

	if(task[projectTypeIds] && task[projectTypeIds]['role']){
		$.each(task[projectTypeIds]['role'], function (k, ele) {
			html += '<option value="'+k+'">'+ele.name+'</option>';
		});

	}
	html +='</select></td>';
	
	html +='<td  class="td4"><span class="hide">周期</span><input type="text" class="" name="taskTime['+template_stage+'][]" placeholder="周期" /></td>'
    html +='<td  class="td5"><span class="hide"></span><select name="roleId['+template_stage+'][]"><option value="">审批流程</option>';
	
	if(task[projectTypeIds] && task[projectTypeIds]['auditor']){
		$.each(task[projectTypeIds]['auditor'], function (k, ele) {
			html += '<option value="'+k+'">'+ele.name+'</option>';
		});

	}
	html +='</select></td>';
    html += '<td  class="td6"><span class="hide">备注</span><input type="text" class="" name="remark['+template_stage+'][]" placeholder="备注" /></td>';
	html += '<td class="w40"><span class="hide"></span><input type="text" class="process" name="level['+template_stage+'][]" value="'+i+'" placeholder=""/></td>';
    html += '<td><div class="icon-remove2" style="width:16px;height=16px;cursor:pointer;background:#fff;"onmousemove="remove_tag(this);" onmouseout="hide_tag(this);"></div></td>';
    html += '</tr>';
   $("select").hide();
	var insertObj;
    if (subTasks.length > 0) {
        insertObj = $("#task_list [data-pid=" + pid + "]:last");
    } else {
        insertObj = $("#task_list [data-id=" + pid + "]");
    }
    //saveTemplateTask();
    insertObj.after(html);
    $("#task_list [edit_flag=1]").find("input:first")[0].focus();
    //console.log(insertObj.find("input[name='taskName']"));
    i++;
}

/**
 * 编辑模板任务
 * @param obj
 */
function editTemplateTask(obj) {
    if ($(obj).attr("edit_flag") != 1) {
        saveTemplateTask();
        $(obj).find("span").hide()
        $(obj).find("input,select").show();
        
        $(obj).attr("edit_flag", "1");
    }
}

/**
 * 保存模板任务
 */
function saveTemplateTask() {
   
   $("#task_list [edit_flag=1]").each(function(i){
       // input
	   $(this).find("input[type='text']").each(function(j){
           var val = $.trim($(this).val());
           var placeholder = $(this).attr("placeholder");
           if (val==""){
               val = placeholder;
           }
           if (placeholder.indexOf("%")>0 && val.indexOf("%")<0){
               $(this).parent().find("span").html(val+"%");
           }else {
               $(this).parent().find("span").html(val);
           }
       })
	   // select
	   $(this).find("select").each(function(j){
           var val = $.trim($(this).val());
			   val = val=="" ? '未选择' : $('.sl_'+val, this).text();
			   // val = val=="" ? '未选择' : task['name'][val];

               $(this).parent().find("span").html(val);
       })		
	   
       $(this).find("span").show();
       $(this).find("input,select").hide();       
	   
	   //$("select").show();
       $(this).attr("edit_flag", "0");
   });
}

function getRandomTaskId() {
    var range = 1000000;
    var rand = 0-Math.random();
    var val = Math.round(rand * range);
    return val;
}

function saveTaskTemplate() {
	
    var projectCategory = $("#projectCategory").data("id");
    $("#projectTypeIds").val(projectCategory);
    var projectStages = '';
    $("#template-task-stage").find("a").each(function(){
        var projectStage = $(this).data("id");
        projectStages += ',' + projectStage;
    });
    if(projectStages != ''){
        $("#projectStages").val(projectStages.substring(1));
    }
    var flag = true;
	var selectRole = true;
    $("#task_list").find("tr").each(function(){
        var tdVal = $.trim($(this).find("td").eq(0).find("input").eq(0).val());
        if(tdVal == ''){
            flag = false;
            return;
        }
		var tdVal = $.trim($(this).find("td").eq(2).find("select").eq(0).val());
		if(tdVal == ''){
            selectRole = false;
            return;
        }
		// var tdVal = $.trim($(this).find("td").eq(4).find("select").eq(0).val());
		// if(tdVal == ''){
            // selectRole = false;
            // return;
        // }
    });
	
	
    if($("#projectTypeIds").val() !='' && $("input[name='name']").val() != '' && flag && selectRole && submitForm){
        submitForm = false;
		var param = $("#createTaskTemplate").serialize();
        $.ajax({
            url: 'backend/template',
            type: 'post',
            dataType: 'json',
            data:param,
            cache: false,
            success: function (data) {
                if(data.flag == 1){
                    window.location.reload();
                }else{
                    alert("添加失败");
                }
            },
            error: function (msg) {
				alert(msg.error);
				// alert(msg);
            }
        });
    }else if($("input[name='name']").val()==''){
        alert("模板名称必填");
    }else if($("#projectTypeIds").val() == ''){
        alert("项目类型必填")
    }else if(!flag){
        alert("任务名称必填");
    }else if(!selectRole){
		alert("项目角色必选");
	}else if(!submitForm){
		alert("提交中，请等待....");
	}

}

/**
 * 隐藏删除按钮
 * @param obj
 */
function hide_tag(obj) {
    $(obj).find("div.icon-remove2").css("background","#fff");
}

/**
 * 显示删除按钮
 * @param obj
 */
function remove_tag(obj) {
    $(obj).find("div.icon-remove2").css("background-image","url(images/icon_remove2.png)");
}

$(document).on("keypress", "#projectStage", function (e) {
    var e = e || event,
        keycode = e.which || e.keyCode;
    if (keycode == 13) {
        var that = $(this);
        var isRepeat = false;
        if($.trim(that.val()) ==''){
            alert("阶段不能为空");
            isRepeat = true;
        }
        that.next().find("li").each(function () {
            if ($(this).text() == that.val()) {
                isRepeat = true;
                return;
            }
        });
        if (!isRepeat) {
            $.ajax({
                url: 'saveProjectStage.htm',
                type: 'post',
                dataType: 'json',
                data:{
                    'name':that.val(),
                    'type':2,
                    'orgId':orgId

                },
                cache: false,
                success: function (data) {
                    if(data.flag == 1){
                        var id = data.id;
                        template_stage = id;
                        addTemplateTaskStageById(id,that.val());
                        var html = '<li data-id="'+id+'" onclick="addTemplateTaskStage(this)">'+that.val()+'</li>';
                        that.next().find(".fudong_add_ul").children().last().before(html);
                    }else{
                        alert("添加失败");
                    }
                },
                error: function (msg) {
                    alert(msg);
                }
            });
        }
    }
});

/**
 * 点击表格之外的地方 把编辑状态设置为显示状态
 */
$(document).click(function(e){
	
    if(e.target.nodeName == 'TD'){
		
        if(!$(e.target.parentElement).hasClass('sub-task') && !$(e.target.parentElement).hasClass('parent-task')){
            saveTemplateTask();
        }
    } else if (e.target.nodeName == 'INPUT' || e.target.nodeName == 'SPAN' || e.target.nodeName == 'P' || e.target.nodeName == 'IMG' || e.target.nodeName == 'SELECT') {
        if (e.target.nodeName == 'SPAN' && !$(e.target).hasClass("icon-add") && !$(e.target.parentElement.parentElement).hasClass('sub-task') && !$(e.target.parentElement.parentElement).hasClass('parent-task')) {
            saveTemplateTask();
        } else if (e.target.nodeName != 'SPAN' && !$(e.target.parentElement.parentElement).hasClass('sub-task') && !$(e.target.parentElement.parentElement).hasClass('parent-task')) {
            saveTemplateTask();
        }
    } else {
        saveTemplateTask();
    }
});

/** 添加子任务按钮*/
$(document).on('click', '.add-sub-task', function (e) {
    var e = e || event, keycode = e.which || e.keyCode;
    $("#task_list1").removeClass('clock');
    addTemplateSubTask($(this).parent());
});

/* 切换到编辑模式 */
$(document).on('click', '.template-task-list td:has(input), .template-task-list td:has(select)', function (e) {
    var e = e || event, keycode = e.which || e.keyCode;

    editTemplateTask($(this).parents("tr"));
    var index = parseInt($(this).index());

    if (index == 0) {
        $(this).parent().find("input").eq(index).focus();
    } else if (index == 1) {
        $(this).parent().find("input").eq(1).focus();
    } else if (index == 3) {
        $(this).parent().find("select").eq(1).focus();
    }else if (index == 5) {
        $(this).parent().find("input").eq(2).focus()
    }else if (index == 2) {
        $(this).parent().find("select").eq(0).focus()
    }else if (index == 4) {
        $(this).parent().find("select").eq(2).focus()
    }else if (index == 6) {
        $(this).parent().find("input").eq(3).focus()
    }
});




/**
 * 设置进度
 */
$(document).on('keyup', '.process', function () {
    isNumOrMoney(this, 1);
});
/**
 * 修改进度
 */
$(document).on('change', '.process', function () {
    calTotalProcess(this);
});

/* 删除任务 */
// $(document).on("click", "#task_list .icon-remove2", function () {
    // removeTask($(this).parents("tr"));
// });

/* 选择阶段 */
$(document).on("click", "#template-task-stage a", function () {
    selectTemplateTaskStage(this);
    template_stage = $(this).data("id");
});

/* 里程碑 */
$(document).on("click", ".task-input-img", function () {
    var flag = $(this).attr("src");
    if (flag.indexOf("on")>0){
        flag = flag.replace("on","off");
        $(this).attr("src",flag);
        $(this).data("state","off");
        $(this).next().val(0);
    }else{
        flag = flag.replace("off","on");
        $(this).attr("src",flag);
        $(this).data("state","on");
        $(this).next().val(1);
    }
});


/* 输入框回车自动保存*/
$(document).on("keypress", "#task_list tr input", function (e) {
    var e = e || event,
        keycode = e.which || e.keyCode;
    if (keycode == 13) {
        saveTemplateTask($(this).parents("td"));
    }
});

/* 删除阶段 */
$(document).on("click", "#template-task-stage .icon-remove2", function () {
    removeTemplateTaskStage($(this).parent());
});

/**
 * 计算总进度
 * @param obj
 */
function calTotalProcess(obj){
    debugger;
    var process = parseFloat($(obj).prev().text().replace("%",""));
    var currProcess = parseFloat($(obj).val().replace("%",""));
    var totalProcess = parseFloat($("#task-percent").text().replace("%",""));
    var totalStageStep = parseFloat($("#totalStageStep").text().replace("%",""));
    var stageStep = parseFloat(changeTwoDecimal_f(totalProcess-process+currProcess));
    $("#task-percent").html(stageStep+"%");
    $("#totalStageStep").html(parseFloat(changeTwoDecimal_f(totalStageStep-totalProcess+stageStep))+"%")

}

/**
 * 删除任务成员
 * @param obj
 */
function removeTaskMember(obj) {
    $(obj).remove();
}
function isNumOrMoney(s, type) {
    //清除“数字”和“.”以外的字符
    if (type == 2) {
        s.value = s.value.replace(/[^\d]/g, "");
    } else if (type == 1) {
        s.value = s.value.replace(/[^\d.]/g, "");
        s.value = s.value.replace(/^\./g, "");  //验证第一个字符是数字而不是.
        s.value = s.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的.
        s.value = s.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    }
}

